package main

import (
	"changeme/module"
	"context"
	"fmt"
	"github.com/mozillazg/go-pinyin"
	"io/ioutil"
	"os/exec"
	"strings"
	"syscall"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called at application startup
func (a *App) startup(ctx context.Context) {
	// Perform your setup here
	a.ctx = ctx
}

// domReady is called after the front-end dom has been loaded
func (a App) domReady(ctx context.Context) {
	// Add your action here
}

// shutdown is called at application termination
func (a *App) shutdown(ctx context.Context) {
	// Perform your teardown here
}

var filePath = "C:\\Windows\\System32\\drivers\\etc\\hosts"

func (a *App) GetHosts() module.ResData {
	var res module.ResData
	file, err := ioutil.ReadFile(filePath)
	if err != nil {
		res.Error = err.Error()
		return res
	}
	res.Data = string(file)
	return res
}

func (a App) SaveHosts(data string) module.ResData {
	var resData module.ResData
	err := ioutil.WriteFile(filePath, []byte(data), 0777)
	if err != nil {
		resData.Error = err.Error()
		return resData
	}
	resData.Data = "保存成功"
	return resData
}

func (a App) SearchPort(port string) module.ResData {
	var resData module.ResData
	cmd := exec.Command("cmd", "/c", "netstat -ano | findstr", port)
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	output, err := cmd.Output()
	if err != nil {
		resData.Error = err.Error()
	}
	fmt.Println(string(output))
	list := strings.Split(string(output), "\n")
	resData.Data = list
	return resData
}

// GetText 文字转拼音
func (a App) GetText(data string) module.ResData {
	var resData module.ResData
	listRes := strings.Split(data, "\n")
	fmt.Println(listRes)
	resStr := []string{}
	for _, item := range listRes {
		resPin := pinyin.NewArgs()
		pinyinStr := pinyin.Pinyin(item, resPin)
		strX := ""
		//循环拼接数组为字符串
		for _, i := range pinyinStr {
			for _, x := range i {
				strX = strX + x
			}
		}
		resStr = append(resStr, strX)
	}
	resData.Data = resStr
	return resData
}
